﻿using Newtonsoft.Json.Linq;
using pixeleditor.WorkingSpace.Resource;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using ttbit.core;

namespace ttbit.WorkingSpace
{

    class Parser_Atlas : IWorkResourceParser
    {



        readonly string[] __exts = new string[] { ".json" };
        public string[] FileExt => __exts;

        public string TypeName => Resource_Atlas.TypeStr;

        public override string ToString()
        {
            return TypeName + "=>" + __exts[0];
        }
        public bool CanCreate => true;
        public IWorkResource Load(bool reimport, System.IO.Stream metaStream, string path)
        {
            //no meta ext
            var name = Path.GetFileNameWithoutExtension(path).ToLower();
            var res = new Resource_Atlas(name);
            try
            {
                var json = System.IO.File.ReadAllText(path);
                var jobj = JObject.Parse(json);
                var list = jobj["atlas"] as JArray;
                for (var i = 0; i < list.Count; i++)
                {
                    res.sprites.Add(list[i].ToString());
                }
            }
            catch (Exception err)
            {

            }


            return res;
        }
        public bool Save(IWorkResource resource, System.IO.Stream metaStream, string path)
        {
            //no meta ext

            var res = resource as Resource_Atlas;


            JObject json = new JObject();
            var jarray = new JArray();
            json["atlas"] = jarray;
            foreach (var sprite in res.sprites)
            {
                jarray.Add(sprite);
            }

            var txt=json.ToString();
            System.IO.File.Delete(path);
            System.IO.File.WriteAllText(path, txt);

            //no need to write to data;
            return true;
        }


    }
}
